//
//  TribeDetailViewController.m
//  yigou
//
//  Created by SunChao on 17/1/19.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "TribeDetailViewController.h"
#import "TribeDetailHeaderView.h"
#import "LUHUnderLineButtonView.h"
#import "ContentListCell.h"
#import "MarketGoodsCell.h"
#import "RankListcell.h"
#import "RQQZModel.h"
#import "MMMarketNew.h"


#import "HisHomePageViewController.h"

#import "TopicleWebViewController.h"
#import "DFLineCellManager.h"
#import "DFBaseLineCell.h"
#import "DFLineLikeItem.h"
#import "DFLineCommentItem.h"
#import "CommentInputView.h"

#import "MMPopupItem.h"
#import "MMSheetView.h"
#import "MMPopupWindow.h"
#import "DFLikeCommentView.h"
#import "YXCustomActionSheet.h"
#import "DyShare.h"
#import "DFImagePreviewViewController.h"

#import "IndexModel.h"
#define kNavigationBtnSpaceHorizontal 5.0f
#define kNavigationBtnSpaceVertical 10.0f
#define kNavigationBtnHeight (self.navigationController.navigationBar.frame.size.height - 2 * kNavigationBtnSpaceVertical)

#define kTitleBarHeight 64.0
#define kBottomBarHeight                    44.0

#define kNavigationBarLeftBtnTag            1000
#define kNavigationBarRightBtnTag            1001
#define kRequestFailRetBtnTag                10000

typedef NS_OPTIONS(NSUInteger, SelectType) {
    SelectTypeTieZi = 1,
    SelectTypeMeiWen ,
    SelectTypeTaoJiangHu,
    SelectTypePaiHangBang
};
@interface TribeDetailViewController ()<UITableViewDelegate,UITableViewDataSource,LUHUnderLineButtonViewDelegate,MarketGoodCellDelegate,DFLineCellDelegate, CommentInputViewDelegate,UINavigationControllerDelegate, DFImagePreviewViewControllerDelegate, YXCustomActionSheetDelegate>
@property (nonatomic,strong)IBOutlet UITableView *tableView;
@property (nonatomic,strong)TribeDetailHeaderView *headView;
@property (nonatomic,strong)NSMutableDictionary *dataSource;
@property (nonatomic,strong)NSMutableArray *tieziArray;
@property (nonatomic,strong)NSMutableArray *meiwenArray;
@property (nonatomic,strong)NSMutableArray *taobaoArray;
@property (nonatomic,strong)NSMutableArray *paihangArray;

@property (nonatomic,assign)NSUInteger selectType;
@property (nonatomic, strong) UIBarButtonItem *settingButtonItem;
@property (nonatomic, strong) UIBarButtonItem     *settingItem;
@property (nonatomic,strong)LUHUnderLineButtonView *buttonView;

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableDictionary *itemDic;

@property (nonatomic, strong) NSMutableDictionary *commentDic;


@property (strong, nonatomic) CommentInputView *commentInputView;


@property (strong, nonatomic) NSString * currentItemId;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@property (assign,nonatomic)BOOL isManger;

@property (assign,nonatomic)BOOL isJoin;

@property (assign,nonatomic)NSInteger tieZiPage;
@property (assign,nonatomic)NSInteger meiwenPage;
@property (assign,nonatomic)NSInteger paiHangPage;
@property (assign,nonatomic)NSInteger paiHangType;

@end

@implementation TribeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tieZiPage = 1;
    self.meiwenPage = 1;
    self.paiHangPage = 1;
    self.paiHangType = 1;
    [self setNavigation];
    NSArray *titles = @[@"帖子",@"美文",@"排行榜"];
    self.buttonView = [[LUHUnderLineButtonView alloc]initWithItems:titles];
    self.buttonView.selectedIndex = 0;
    _selectType = SelectTypeTieZi;
    self.buttonView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
    self.buttonView.delegate = self;
    TribeDetailHeaderView *headview = [[TribeDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 218+195+30+64+20)];
    headview.vc = self;
    self.headView = headview;
    self.headView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableHeaderView = self.headView;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.dataSource = [NSMutableDictionary new];
    self.tieziArray  = [NSMutableArray array];
    self.meiwenArray  = [NSMutableArray array];
    self.taobaoArray  = [NSMutableArray array];
    self.paihangArray  = [NSMutableArray array];
    
    _items = [NSMutableArray array];
    
    _itemDic = [NSMutableDictionary dictionary];
    
    _commentDic = [NSMutableDictionary dictionary];
    
    [self initCommentInputView];

    [self loadNetworkData];//排行
    [self loadNetworkDataByTypeTieZiOrMenWenWithType00];//帖子
    [self loadNetworkDataByTypeTieZiOrMenWenWithType01];//美文
    [self loadNetworkDataByTypeAllGoodsList];
    _selectType =  SelectTypeTieZi;
    [self addLoadMoreFooter:self.tableView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ChangeGuanLiButton) name:@"ChangeGuanLiButton" object:nil];
    
}
- (void)ChangeGuanLiButton{
    
    if (_selectType == SelectTypePaiHangBang) {
        if (self.paiHangType ==1) {
            self.paiHangType =2;
        }else if (self.paiHangType ==2){
            self.paiHangType = 1;
        }
        
        [self.tableView reloadData];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationController.navigationBar.translucent = YES;
    [_commentInputView addNotify];
    
    [_commentInputView addObserver];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_commentInputView removeNotify];
    
    [_commentInputView removeObserver];
    self.navigationController.navigationBar.translucent = NO;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"HiddenCommentBar" object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"HiddenCommentBar" object:nil];
}

- (void)setNavigation{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.navigationController.navigationBar.translucent = YES;
   
    [self.navigationController.navigationBar setBackgroundImage:[self createImageWithColor:[UIColor clearColor] ]
                                                 forBarPosition:UIBarPositionAny
                                                     barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    //解决出现的那条线
//    tools.clipsToBounds = YES;
    //解决tools背景颜色的问题
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    [self showNavBarWithRightOneImage:[UIImage imageNamed:@"goodshare"] andRightTwoImage:[UIImage imageNamed:@"topsearch"] andRightOneAction:@selector(oneAction:) andRighTwoAction:@selector(twoAction:)];
    UIEdgeInsets contentInset = self.tableView.contentInset;
    contentInset.top = -64;
    [self.tableView setContentInset:contentInset];
}

- (void)oneAction:(UIButton *)button{
     NSLog(@"点击更多");
    UIAlertController *alertController = [[UIAlertController alloc]init];
    if (_isManger == YES) {
        
        // 当前用户是酋长
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
        }];
        
        UIAlertAction *shareAction = [UIAlertAction actionWithTitle:@"分享部落" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self ShareAcion];
        }];
        
        
//        UIAlertAction *dissolveAction = [UIAlertAction actionWithTitle:@"解散部落" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            NSLog(@"解散部落");
//            [self DissolveAction];
//        }];
        
        UIAlertAction *reportAction = [UIAlertAction actionWithTitle:@"举报部落" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            [self ReportAction];
            NSLog(@"举报部落");
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:shareAction];
//        [alertController addAction:dissolveAction];
        [alertController addAction:reportAction];
        
    }else{
     
        // 当前用户不是酋长
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
        }];
        
        UIAlertAction *shareAction = [UIAlertAction actionWithTitle:@"分享部落" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"分享部落");
            [self ShareAcion];
        }];
        
        
        UIAlertAction *joinAction = nil;
        if (_isJoin == YES) {
            //当前用户已加入该部落
            joinAction = [UIAlertAction actionWithTitle:@"退出部落" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"退出部落");
                [self QuitTribe];
            }];
            //当前用户没有加入该部落
        }else{
            joinAction = [UIAlertAction actionWithTitle:@"加入部落" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"加入部落");
                [self JoinTribe];
            }];
        }
       
        
        UIAlertAction *reportAction = [UIAlertAction actionWithTitle:@"举报部落" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            NSLog(@"举报部落");
             [self ReportAction];
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:shareAction];
        [alertController addAction:joinAction];
        [alertController addAction:reportAction];
        
    }
    
    [self presentViewController:alertController animated:YES completion:^{
        NSLog(@"presented");
    }];
}

- (void)ShareAcion{
    NSLog(@"ShareAcion");
    [self clickShare];
}

- (void)DissolveAction{
    NSLog(@"DissolveAction");
    DYBaseRequest *request = [DYBaseRequest new];
    
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addReport?report_obj=%@&report_obj_id=%@&report_type=%@&report_content=%@", APIYIGOU, @"05", _tribeID, @"00", @""];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"举报成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"举报失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];

}
- (void)ReportAction{
    NSLog(@"ReportAction");
    DYBaseRequest *request = [DYBaseRequest new];
    
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/addReport?report_obj=%@&report_obj_id=%@&report_type=%@&report_content=%@", APIYIGOU, @"05", _tribeID, @"00", @""];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"举报成功！"];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:@"举报失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (void)QuitTribe{
    NSLog(@"QuitTribe");
    NSString *type = @"quitTribe";
    [self loadNetworkDataByTypeJoinOrQuitTribe:type];
}
- (void)JoinTribe{
    NSLog(@"JoinTribe");
    NSString *type = @"joinTribe";
    [self loadNetworkDataByTypeJoinOrQuitTribe:type];
    
}

- (void)twoAction:(UIButton *)button{
   
    NSLog(@"点击搜索");
}

- (void)clickShare {
    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
    cusSheet.delegate = self;
    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
                              @{@"name":@"微信",@"icon":@"sns_wx"},
                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},];
    
    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
}

- (void)customActionSheetButtonClick:(YXActionSheetButton *)btn {
    NSLog(@"第%li个按钮被点击了",(long)btn.tag);
    NSInteger index = btn.tag;
    
    DyShareType type;
    switch (index) {
        case 0:
            type = DyShareTypePengYouQuan;
            break;
        case 4:
            type = DyShareTypeQZone;
            break;
        case 2:
            type = DyShareTypeWeiBo;
            break;
        case 1:
            type = DyShareTypeWeiXin;
            break;
        case 3:
            type = DyShareTypeQQ;
            break;
        default:
            break;
    }
    
    NSDictionary *dic = [self.dataSource objectForKey:@"tribeInfo"];
   
    NSString *desc = [NSString stringWithFormat:@"%@  %@",[dic objectForKey:@"tribe_name"],[dic objectForKey:@"tribe_desc"]];
    [[DyShare getInstance]shareWithShareType:type Content:@"" title:desc url:[dic objectForKey:@"shareUrl"] image:self.headView.bgImgView.image delegate:nil];
}


- (void)loadNetworkDataByTypeJoinOrQuitTribe:(NSString *)type{
    
    NSString *url = @"";
    DYBaseRequest *request = [DYBaseRequest new];
    if ([type isEqualToString:@"quitTribe"]) {
        url = [NSString stringWithFormat:@"%@/hytribe/outTribe?tribe_id=%@", APIYIGOU,_tribeID];
    }else if ([type isEqualToString:@"joinTribe"]){
         url = [NSString stringWithFormat:@"%@/hytribe/joinTribe?tribe_id=%@", APIYIGOU,_tribeID];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        if ([type isEqualToString:@"quitTribe"]) {
            [ViewFactory showSuccess:@"退出成功"];
            [self goPop];
        }else if ([type isEqualToString:@"joinTribe"]){
            _isJoin = YES;
             [ViewFactory showSuccess:@"加入成功"];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"joinTribeNotification" object:nil];
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
    
}
- (void)showNavBarWithRightOneImage:(UIImage *)rightOneImage
                   andRightTwoImage:(UIImage *)rightTwoImage
                  andRightOneAction:(SEL)ractionOne
                   andRighTwoAction:(SEL)ractionTwo{
    
    UIButton *btnRightOne = [UIButton buttonWithType:UIButtonTypeCustom];
    UIBarButtonItem *rigthBar = [[UIBarButtonItem alloc] initWithCustomView:btnRightOne];
    [btnRightOne setBackgroundImage:rightOneImage forState:UIControlStateNormal];
    btnRightOne.adjustsImageWhenHighlighted = NO;
    btnRightOne.contentMode = UIViewContentModeScaleAspectFit;
    btnRightOne.tag = kNavigationBarLeftBtnTag;
    CGFloat heightOne = kNavigationBtnHeight;
    CGFloat widthOne = heightOne * rightOneImage.size.width / rightOneImage.size.height;
    if (heightOne/widthOne < 0.8) {
        CGFloat scale = rightOneImage.size.height / rightOneImage.size.width;
        btnRightOne.frame = CGRectMake(SCREEN_WIDTH - (SCREEN_WIDTH - heightOne - 10),
                                       kNavigationBtnSpaceHorizontal,
                                       heightOne,
                                       heightOne*scale);
    } else {
        btnRightOne.frame = CGRectMake(SCREEN_WIDTH - (SCREEN_WIDTH - widthOne ),
                                       kNavigationBtnSpaceHorizontal,
                                       widthOne,
                                       heightOne);
    }
    [btnRightOne setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnRightOne addTarget:self action:ractionOne forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btnRightTwo = [UIButton buttonWithType:UIButtonTypeCustom];
    UIBarButtonItem *rigthBarTwo = [[UIBarButtonItem alloc] initWithCustomView:btnRightTwo];
    [btnRightTwo setBackgroundImage:rightTwoImage forState:UIControlStateNormal];
    btnRightTwo.adjustsImageWhenHighlighted = NO;
    btnRightTwo.contentMode = UIViewContentModeScaleAspectFit;
    btnRightTwo.tag = kNavigationBarLeftBtnTag;
    btnRightTwo.hidden = YES;
    CGFloat heightTwo = kNavigationBtnHeight;
    CGFloat widthTwo = heightTwo * rightTwoImage.size.width / rightTwoImage.size.height;
    if (heightTwo/widthTwo < 0.8) {
        CGFloat scale = rightTwoImage.size.height / rightTwoImage.size.width;
        btnRightTwo.frame = CGRectMake(SCREEN_WIDTH - (SCREEN_WIDTH - heightTwo - heightOne - 10 ),
                                       kNavigationBtnSpaceHorizontal,
                                       heightTwo,
                                       heightTwo*scale);
    } else {
        btnRightTwo.frame = CGRectMake(SCREEN_WIDTH - (SCREEN_WIDTH - widthTwo - widthOne ),
                                       kNavigationBtnSpaceHorizontal,
                                       widthTwo,
                                       heightTwo);
    }
    [btnRightTwo setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnRightTwo addTarget:self action:ractionTwo forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *negativeSpacerRight = [[UIBarButtonItem alloc]
                                            initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                            target:nil action:nil];
    negativeSpacerRight.width = -5;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacerRight,rigthBar,negativeSpacerRight,negativeSpacerRight,rigthBarTwo, nil];
    
}

-(UIImage*) createImageWithColor:(UIColor*) color{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
- (void)goPop {
   
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectedIndexBtn:(NSInteger)button{
    switch (button) {
        case 0:
            _selectType = SelectTypeTieZi;
            break;
        case 1:
            _selectType = SelectTypeMeiWen;
            break;
        case 2:
            _selectType = SelectTypeTaoJiangHu;
            _selectType = SelectTypePaiHangBang;
            break;
//        case 3:
//            _selectType = SelectTypePaiHangBang;
//            break;
        default:
            break;
    }
        [self.tableView reloadData];
    
}
//获取部落详情下所有数据主要用于排行榜数据
- (void)loadNetworkData {
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/tribeDetail?tribe_id=%@", APIYIGOU,_tribeID];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSLog(@"------%@",request);
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic =  [dict objectForKey:@"data"];
        _isManger = [[dataDic objectForKey:@"isManger"]boolValue];
        NSDictionary *tribeInfo = [dataDic objectForKey:@"tribeInfo"];
        _isJoin = [[tribeInfo objectForKey:@"is_join"]boolValue];
        [self.paihangArray addObject:[dataDic objectForKey:@"mangerUser"]];
        NSDictionary *tmpDic = [dataDic objectForKey:@"tribeMemberRank"];
        NSArray *list = [tmpDic objectForKey:@"list"];
        [self.paihangArray addObjectsFromArray:list];
        NSDictionary *tmpDic2 = [dataDic objectForKey:@"tribeInfo"];
        [self.dataSource setObject:tmpDic2 forKey:@"tribeInfo"];
        [self loadNetworkDataTopMsg1];
        NSLog(@"paihang:%@",self.paihangArray);
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)loadNetworkDataTopMsg1 {
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/getTopMsg?tribe_id=%@&top_type=%@", APIYIGOU, _tribeID,@"01"];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [dict objectForKey:@"data"];
        if (array.count>0) {
            
            [self.dataSource setObject:array forKey:@"topData1"];
            
        }
        
        [self loadNetworkDataTopMsg2];
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}


- (void)loadNetworkDataTopMsg2 {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/getTopMsg?tribe_id=%@&top_type=%@", APIYIGOU, _tribeID,@"02"];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
    
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [dict objectForKey:@"data"];
        if (array.count>0) {
            [self.dataSource setObject:array forKey:@"topData2"];
        }
        
        [self loadNetworkDataTopMsg3];
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}


- (void)loadNetworkDataTopMsg3 {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/getTopMsg?tribe_id=%@&top_type=%@", APIYIGOU, _tribeID,@"03"];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
    
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
       NSArray *array = [dict objectForKey:@"data"];
        if (array.count>0) {
            [self.dataSource setObject:array forKey:@"topData3"];
        }
        self.headView.dataSource = self.dataSource;
        [self.headView refreshHeaderViewData:self.dataSource];
        self.headView.tribeID = self.tribeID;
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)loadNetworkDataByTypeTieZiOrMenWenWithType00 {
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSInteger pageStart = 1;
    NSInteger pageSize = 5;
    NSString  *contentType = @"00";
    
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/getContentByType?contentType=%@&tribe_id=%@&page=%ld&limit=%ld", APIYIGOU, contentType,_tribeID,(long)pageStart,(long)pageSize];
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSLog(@"------%@",request);
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic =  [dict objectForKey:@"data"];
        self.tieziArray = [dataDic objectForKey:@"list"];
        NSLog(@"tiezi:%@",self.tieziArray);
        [self initDataWithArray:self.tieziArray];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

- (void)loadNetworkDataByTypeTieZiOrMenWenWithType01 {
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSInteger pageStart = 1;
    NSInteger pageSize = 5;
    NSString *contentType = @"01";
    NSString *url = [NSString stringWithFormat:@"%@/hyContent/getContentByType?contentType=%@&tribe_id=%@&page=%ld&limit=%ld", APIYIGOU, contentType,_tribeID,(long)pageStart,(long)pageSize];
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSLog(@"------%@",request);
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic =  [dict objectForKey:@"data"];
        self.meiwenArray = [dataDic objectForKey:@"list"];
        NSLog(@"meiwen:%@",self.meiwenArray);
        
    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}


- (void)loadNetworkDataByTypeAllGoodsList{
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSInteger pageStart = 1;
    NSInteger pageSize = 5;
   
    NSString *url = [NSString stringWithFormat:@"%@/hytribe/selectTribeAllGoodsList?tribe_id=%@&page=%ld&limit=%ld", APIYIGOU,_tribeID ,(long)pageStart,(long)pageSize];
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSLog(@"------%@",request);
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic =  [dict objectForKey:@"data"];
        self.taobaoArray = [dataDic objectForKey:@"list"];
        NSLog(@"meiwen:%@",self.taobaoArray);
         NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *tmpDic in self.taobaoArray) {
            MMMarketNew *market = [[MMMarketNew alloc]initWithDictionary:tmpDic error:nil];
            [array addObject:market];
        }
        [self.taobaoArray removeAllObjects];
        self.taobaoArray = array;

    } error:^(YTKBaseRequest *request) {
        NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        
    }];
}

-(void)loadMore
{
    [super loadMore];
    DYBaseRequest *request = [DYBaseRequest new];
    
    NSInteger pageSize = 5;
    NSString *url = @"";
    
    if (_selectType == SelectTypeTieZi) {
        NSString *contentType = @"00";
        self.tieZiPage += 1;
         url = [NSString stringWithFormat:@"%@/hyContent/getContentByType?contentType=%@&tribe_id=%@&page=%ld&limit=%ld", APIYIGOU, contentType,_tribeID,self.tieZiPage,(long)pageSize];
    }
    if (_selectType == SelectTypeMeiWen) {
        self.meiwenPage += 1;
         NSString *contentType = @"01";
         url = [NSString stringWithFormat:@"%@/hyContent/getContentByType?contentType=%@&tribe_id=%@&page=%ld&limit=%ld", APIYIGOU, contentType,_tribeID,self.meiwenPage,(long)pageSize];
    }
    if (_selectType == SelectTypePaiHangBang) {
        self.paiHangPage += 1;
        pageSize = 10;
       NSDictionary *dict = [self.dataSource objectForKey:@"tribeInfo"];
        NSString *tribe_id = [dict objectForKey:@"tribe_id"];
         url = [NSString stringWithFormat:@"%@/hytribe/getTribeMemberRank?contentType=%@&tribe_id=%@&page=%ld&limit=%ld", APIYIGOU, tribe_id,_tribeID,self.paiHangPage,(long)pageSize];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *dataDic = [dict objectForKey:@"data"];
        NSArray *addTopicListArr = [dataDic objectForKey:@"list"];
        if (addTopicListArr.count == 0) {
            [ViewFactory showSuccess:@"没有更多数据了！"];
             [self.tableView.mj_footer endRefreshing];
            return ;
        }
        if (_selectType == SelectTypeTieZi) {
            [self initDataWithArray:addTopicListArr];
        }
        if (_selectType == SelectTypeMeiWen) {
            for (NSDictionary *tmpDic in addTopicListArr) {
                [self.meiwenArray addObject:tmpDic];
            }
        }
        if (_selectType == SelectTypePaiHangBang) {
            for (NSDictionary *tmpDic in addTopicListArr) {
                [self.paihangArray addObject:tmpDic];
            }
        }
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
        
    } error:^(YTKBaseRequest *request) {
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma tableView -mark DataSource & Delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return _buttonView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_selectType == SelectTypeTieZi) {
        
        return _items.count;
       
    }else if (_selectType == SelectTypeMeiWen){
       return self.meiwenArray.count;
    }else if (_selectType == SelectTypeTaoJiangHu){
        return self.taobaoArray.count/2+self.taobaoArray.count%2+1;
    }else if (_selectType == SelectTypePaiHangBang){
        return self.paihangArray.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
     if(_selectType == SelectTypeTieZi){
         DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
         DFBaseLineCell *typeCell = [self getCell:[item class]];
         
         NSString *reuseIdentifier = NSStringFromClass([typeCell class]);
         DFBaseLineCell *cell = [tableView dequeueReusableCellWithIdentifier: reuseIdentifier];
         if (cell == nil ) {
             cell = [[[typeCell class] alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier isManger:_isManger];
         }else{
             NSLog(@"重用Cell: %@", reuseIdentifier);
         }
         
         cell.delegate = self;
         
         cell.separatorInset = UIEdgeInsetsZero;
         if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
             cell.layoutMargins = UIEdgeInsetsZero;
         }
         [cell updateWithItem:item];
         
         return cell;
    }
//     else if(_selectType == SelectTypeTaoJiangHu){
//         if (indexPath.row == 0) {
//             UITableViewCell *cell = [[UITableViewCell  alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 15)];
//             cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
//             return cell;
//         }
//         MarketGoodsCell *cell = GET_CELL(MarketGoodsCell,@"MarketGoodsCell");
//         [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//         cell.titleH.constant = 0;
//         cell.lineH.constant = 0;
//         cell.title.hidden = YES;
//         cell.line.hidden = YES;
//         MMMarketNew *ldata = nil;
//         MMMarketNew *rdata = nil;
//         if (self.taobaoArray.count > (indexPath.row-1) * 2) {
//             ldata = [self.taobaoArray objectAtIndex:((indexPath.row-1) * 2)];
//         }
//         if (self.taobaoArray.count > (indexPath.row-1) * 2 + 1) {
//             rdata = [self.taobaoArray objectAtIndex:((indexPath.row-1) * 2 + 1)];
//         }
//         
//         cell.type = IMarketGoodCellNew;
//         cell.index = indexPath.row;
//         cell.delegate = self;
//        [cell fillWithData:ldata right:rdata];
//         return cell;
//     }
     else if(_selectType == SelectTypePaiHangBang){
         NSMutableDictionary *dict = [NSMutableDictionary new];
         dict = [self.paihangArray objectAtIndex:indexPath.row];
         [dict setObject:self.tribeID forKey:@"tribe_id"];
         if (indexPath.row == 0) {
            RankListcell *cell = GET_CELL(RankListcell,@"RankListcell");
              [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
             cell.model = [[RQQZModel alloc]initWithDictionary:dict error:nil];
            
              cell.type = @"00";
             if (_isManger == YES) {
                 cell.isManger =YES;
             }else{
                 cell.isManger = NO;
             }
             [cell contentWithDic:dict type:cell.type];
            
            cell.contentView.frame = CGRectMake(0, cell.frame.origin.y+15, cell.frame.size.width, cell.frame.size.height-30);
             return cell;
         }else{
             RankListcell *cell = GET_CELL(RankListcell,@"RankListcell");
             [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
             cell.type = @"01";
             if (self.paiHangType == 1) {
                 if (_isManger == YES) {
                     cell.jinYanOrGuanZhuType = 1;
                     cell.isManger =YES;
                     
                 }else{
                     cell.isManger = NO;
                 }
                 [cell contentWithDic:dict type:cell.type];
             }else if (self.paiHangType == 2){
                 if (_isManger == YES) {
                     cell.jinYanOrGuanZhuType = 2;
                     cell.isManger =YES;
                 }else{
                     cell.isManger = NO;
                 }
                 [cell contentWithDic:dict type:cell.type];
             }
             
             return cell;
         }
     }else if(_selectType == SelectTypeMeiWen){
         ContentListCell *cell = GET_CELL(ContentListCell,@"ContentListCell");
         [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
         NSDictionary *dict = [self.meiwenArray objectAtIndex:indexPath.row];
         [cell contentWithDic:[dict objectForKey:@"hotTopic"]];
         return cell;
         
     }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_selectType == SelectTypeTieZi){
        DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
        DFBaseLineCell *typeCell = [self getCell:[item class]];
        return [typeCell getReuseableCellHeight:item]+40;
    }else if (_selectType == SelectTypeMeiWen){
        return 440;
    }else if (_selectType == SelectTypeTaoJiangHu){
        if (indexPath.row == 0) {
            return 15;
        }
         return 280;
    }else if (_selectType == SelectTypePaiHangBang){
        
        if (indexPath.row == 0) {
            return 130;
        }
        return 100;
    }
    return 0;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if(_selectType == SelectTypeTieZi){
       
    }else if (_selectType == SelectTypeMeiWen){
        
        
    }else if (_selectType == SelectTypeTaoJiangHu){
        
        
    }else if (_selectType == SelectTypePaiHangBang){
        
       NSDictionary *dic = [self.paihangArray objectAtIndex:indexPath.row];
        NSString *userId = [dic objectForKey:@"user_id"];
        [self PushToHisHomePageWithId:userId];
    }
}

- (void)PushToHisHomePageWithId:(NSString *)userId{
    HisHomePageViewController *homepage = [[HisHomePageViewController alloc]init];
    homepage.userid = userId;
    [self.navigationController pushViewController:homepage animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //scrollView已经有拖拽手势，直接拿到scrollView的拖拽手势
    UIPanGestureRecognizer *pan = scrollView.panGestureRecognizer;
    //获取到拖拽的速度 >0 向下拖动 <0 向上拖动
    CGFloat velocity = [pan velocityInView:scrollView].y;
    
    if (velocity <- 50) {
        self.navigationController.navigationBar.translucent = NO;
        UIEdgeInsets contentInset = self.tableView.contentInset;
        contentInset.top = 0;
        [self.tableView setContentInset:contentInset];

    }else if (velocity > 50) {
        //向下拖动，隐藏导航栏
        if (self.tableView.contentOffset.y<200) {
            UIEdgeInsets contentInset = self.tableView.contentInset;
            contentInset.top = 0;
            [self.tableView setContentInset:contentInset];
            self.navigationController.navigationBar.translucent = YES;
        }
       
        
    }else if(velocity == 0){
        //停止拖拽
        if (self.tableView.contentOffset.y<100) {
            UIEdgeInsets contentInset = self.tableView.contentInset;
            contentInset.top = 0;
            [self.tableView setContentInset:contentInset];
            self.navigationController.navigationBar.translucent = YES;
        }
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"HiddenCommentBar" object:nil];

}
#pragma mark 淘宝相关代理方法
- (void)clickMarketGoodCell:(NSInteger)index isLeft:(BOOL)clickLeft myType:(MarketGoodCellType)type{
    MMMarketNew *gooddata = nil;
    if (clickLeft) {
        gooddata = [self.taobaoArray objectAtIndex:(index-1) * 2];
    } else {
        gooddata = [self.taobaoArray objectAtIndex:((index-1) * 2 + 1)];
    }
    
    if (gooddata) {
        [[GoToManager sharedGoToManager] go:self type:ToGoodDetail data:gooddata];
    }
}
#pragma mark 美文相关方法

- (void)AddCommentDataRequestWithReplyCommentId:(NSString *)replyCommentId ContentId:(NSString *)contentId CommentText:(NSString *)text{
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:@"评论失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}
//初始化文章数据
-(void) initDataWithArray:(NSArray *)array
{
    
    NSArray *topicArr = array;
    NSMutableDictionary *topicDic = [NSMutableDictionary new];
    for (NSDictionary *tmpDic in topicArr) {
        if ([tmpDic.allKeys containsObject:@"topic"]) {
            topicDic = [tmpDic objectForKey:@"topic"];
        }else if ([tmpDic.allKeys containsObject:@"hotTopic"]){
            topicDic = [tmpDic objectForKey:@"hotTopic"];
        }else if ([tmpDic.allKeys containsObject:@"content"]){
            topicDic = [tmpDic objectForKey:@"content"];
        }
        DFTextImageLineItem *textImageItem = [[DFTextImageLineItem alloc] init];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.user_id = [topicDic objectForKey:@"user_id"];
        textImageItem.head_url = [[topicDic objectForKey:@"hyUser"] objectForKey:@"head_url"];
        textImageItem.nick_name = [[topicDic objectForKey:@"hyUser"] objectForKey:@"nick_name"];
        textImageItem.title = [topicDic objectForKey:@"title"];
        textImageItem.text = [topicDic objectForKey:@"content_desc"];
        textImageItem.tribe_name = [topicDic objectForKey:@"tribe_name"];
        textImageItem.publish_tm = [topicDic objectForKey:@"publish_tm"];
        textImageItem.content_id = [topicDic objectForKey:@"content_id"];
        textImageItem.tribe_id = [topicDic objectForKey:@"tribe_id"];
        textImageItem.shareUrl = [topicDic objectForKey:@"shareUrl"];
        textImageItem.cover_img = [topicDic objectForKey:@"cover_img"];
        NSArray *picArr = [topicDic objectForKey:@"mediaList"];
        NSMutableArray *srcImages = [NSMutableArray array];
        for (NSDictionary *tmpDic in picArr) {
            NSString *imgString =  [tmpDic objectForKey:@"media_url"];
            [srcImages addObject:imgString];
        }
        [textImageItem.srcImages removeAllObjects];
        
        textImageItem.srcImages = srcImages;
        
        NSArray *contentCmt = [tmpDic objectForKey:@"contentCmtList"];
        
        for (NSDictionary *cmtDic in contentCmt) {
            NSLog(@"cmtArr:%@",cmtDic);
            DFLineCommentItem *commentItem1_1 = [[DFLineCommentItem alloc] init];
            commentItem1_1.commentId = [cmtDic objectForKey:@"comment_id"];
            commentItem1_1.userId = [cmtDic objectForKey:@"user_id"];
            commentItem1_1.userNick = [cmtDic objectForKey:@"user_nike_name"];
            if (![[cmtDic objectForKey:@"reply_user_id"]isEqualToString:@""]) {
                commentItem1_1.replyUserId = [cmtDic objectForKey:@"reply_user_id"];
                commentItem1_1.replyUserNick = [cmtDic objectForKey:@"reply_user_nike_name"];
            }
            
            commentItem1_1.text = [cmtDic objectForKey:@"comment"];
            
            [textImageItem.comments addObject:commentItem1_1];
        }
        
        NSArray *contentLike = [tmpDic objectForKey:@"contentLikeList"];
        [textImageItem.likes removeAllObjects];
        for (NSDictionary *tmpDic in contentLike) {
            DFLineLikeItem *likeItem1_1 = [[DFLineLikeItem alloc] init];
            likeItem1_1.userId = [tmpDic objectForKey:@"user_id"];
            likeItem1_1.userNick = [tmpDic objectForKey:@"nick_name"];
            likeItem1_1.head_url = [tmpDic objectForKey:@"head_url"];
            [textImageItem.likes addObject:likeItem1_1];
        }
        [self addItem:textImageItem];
    }
    
}

#pragma mark - Method

-(DFBaseLineCell *) getCell:(Class)itemClass
{
    DFLineCellManager *manager = [DFLineCellManager sharedInstance];
    return [manager getCell:itemClass];
}

-(void)addItem:(DFBaseLineItem *)item
{
    [self insertItem:item index:_items.count];
}

-(void) addItemTop:(DFBaseLineItem *) item
{
    [self insertItem:item index:0];
}

-(void) insertItem:(DFBaseLineItem *) item index:(NSUInteger)index
{
    [self genCommentAttrString:item];
    
    [_items insertObject:item atIndex:index];
    
    
    [_itemDic setObject:item forKey:item.content_id];
    
}

-(DFBaseLineItem *) getItem:(NSString *) itemId
{
    return [_itemDic objectForKey:itemId];
    
}

-(void)addCommentItem:(DFLineCommentItem *)commentItem itemId:(NSString *)itemId replyCommentId:(NSString *)replyCommentId

{
    NSString *contentId = itemId;
    NSString *text = commentItem.text;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = @"";
    if (replyCommentId == 0) {
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?content_id=%@&comment=%@", APIYIGOU,contentId,text];
    }else{
        url = [NSString stringWithFormat:@"%@/hyContent/addComment?reply_comment_id=%@&content_id=%@&comment=%@", APIYIGOU,replyCommentId,contentId,text];
    }
    
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [ViewFactory showSuccess:@"评论成功"];
        DFBaseLineItem *item = [self getItem:itemId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        [tmpArr addObject:commentItem];
        [tmpArr addObjectsFromArray:item.comments];
        [item.comments removeAllObjects];
        item.comments = tmpArr;
        //[self AddCommentDataRequestWithReplyCommentId:replyCommentId ContentId:itemId CommentText:commentItem.text];
        if (![replyCommentId isEqualToString:@"0"]) {
            DFLineCommentItem *replyCommentItem = [self getCommentItem:replyCommentId];
            
            commentItem.replyUserId = replyCommentItem.userId;
            commentItem.replyUserNick = replyCommentItem.userNick;
            
        }
        
        item.cellHeight = 0;
        [self genCommentAttrString:item];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
        [ViewFactory showErrorStrMsg:@"评论失败！"];
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
    
}

-(void) genCommentAttrString:(DFBaseLineItem *)item
{
    NSMutableArray *comments = item.comments;
    
    [item.commentStrArray removeAllObjects];
    
    for (int i=0; i<comments.count;i++) {
        DFLineCommentItem *comment = [comments objectAtIndex:i];
        [_commentDic setObject:comment forKey:comment.commentId];
        
        NSString *resultStr;
        if (comment.replyUserId == 0) {
            resultStr = [NSString stringWithFormat:@"%@: %@",comment.userNick, comment.text];
        }else{
            resultStr = [NSString stringWithFormat:@"%@回复%@: %@",comment.userNick, comment.replyUserNick, comment.text];
        }
        
        NSMutableAttributedString *commentStr = [[NSMutableAttributedString alloc]initWithString:resultStr];
        if (comment.replyUserId == 0) {
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(0, comment.userNick.length)];
        }else{
            NSUInteger localPos = 0;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.userId] range:NSMakeRange(localPos, comment.userNick.length)];
            localPos += comment.userNick.length + 2;
            [commentStr addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"%@", comment.replyUserId] range:NSMakeRange(localPos, comment.replyUserNick.length)];
        }
        
        NSLog(@"ffff: %@", resultStr);
        
        [item.commentStrArray addObject:commentStr];
    }
}
-(void)onLike:(NSString *)contentId likeItem:(DFLineLikeItem *)likeItem type:(BOOL)type
{
    //点赞
    if (type) {
        
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        [tmpArr addObjectsFromArray:item.likes];
        [item.likes removeAllObjects];
        item.likes = tmpArr;
    }else {
        DFBaseLineItem *item = [self getItem:contentId];
        NSMutableArray *tmpArr = [NSMutableArray new];
        DFLineLikeItem *likeItem = [[DFLineLikeItem alloc] init];
        likeItem.userId = [UserData userid];
        likeItem.userNick = [UserData username];
        likeItem.head_url = [UserData userheadurl];
        [tmpArr addObject:likeItem];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i<item.likes.count; i++) {
            DFLineLikeItem *tmpItem =  [item.likes objectAtIndex:i];
            if ([tmpItem.userId isEqualToString:likeItem.userId]) {
                //                NSLog(@"有一样的");
                [array addObject:tmpItem];
            }
        }
        [item.likes removeObjectsInArray:array];
    }
    
    [self.tableView reloadData];
}

-(DFLineCommentItem *)getCommentItem:(NSString *)commentId
{
    return [_commentDic objectForKey:commentId];
}

-(void) initCommentInputView
{
    if (_commentInputView == nil) {
        _commentInputView = [[CommentInputView alloc] initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
        _commentInputView.hidden = YES;
        _commentInputView.delegate = self;
        [self.view addSubview:_commentInputView];
    }
    
}
#pragma mark - DFLineCellDelegate


-(void)onComment:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.commentId = @"0";
    
    _commentInputView.hidden = NO;
    
    [_commentInputView show];
}

//-(void)onShare:(NSString *)itemId
//{
//    YXCustomActionSheet *cusSheet = [[YXCustomActionSheet alloc] init];
//    cusSheet.delegate = self;
//    NSArray *contentArray = @[@{@"name":@"朋友圈",@"icon":@"sns_pyq"},
//                              @{@"name":@"微信",@"icon":@"sns_wx"},
//                              @{@"name":@"新浪微博",@"icon":@"sns_wb"},
//                              @{@"name":@"QQ ",@"icon":@"sns_qq"},
//                              @{@"name":@"QQ空间 ",@"icon":@"sns_qzone"},];
//    
//    [cusSheet showInView:[UIApplication sharedApplication].keyWindow contentArray:contentArray];
//}


//- (void)onClickTitleLabel:(NSString *)tribeId
//{
//    TribeDetailViewController *detail = [[TribeDetailViewController alloc]initWithNibName:@"TribeDetailViewController" bundle:nil];
//    [self.navigationController pushViewController:detail animated:YES];
//    detail.tribeID = tribeId;
//}

//点击左边头像 或者 点击评论和赞的用户昵称
//-(void)onClickUser:(NSString *)userId
//{
//    NSLog(@"userid:%@",userId);
//    UserViewController *controller = [[UserViewController alloc] init];
//    [self.navigationController pushViewController:controller animated:YES];
//    
//}
//-(void)onClickHeaderUserAvatar
//{
//    [self onClickUser:@"111"];
//}


-(void)onClickComment:(NSString *)commentId itemId:(NSString *)itemId
{
    _currentItemId = itemId;
    
    _commentInputView.hidden = NO;
    
    _commentInputView.commentId = commentId;
    
    [_commentInputView show];
    
    DFLineCommentItem *comment = [_commentDic objectForKey:commentId];
    [_commentInputView setPlaceHolder:[NSString stringWithFormat:@"  回复: %@", comment.userNick]];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text
{
    [self onCommentCreate:commentId text:text itemId:_currentItemId];
}


-(void)onCommentCreate:(NSString *)commentId text:(NSString *)text itemId:(NSString *) itemId
{
    
    DFLineCommentItem *commentItem = [[DFLineCommentItem alloc] init];
    commentItem.commentId = commentId;
    commentItem.userId = [UserData userid];
    commentItem.userNick = [UserData username];
    commentItem.text = text;
    [self addCommentItem:commentItem itemId:itemId replyCommentId:commentId];
}





#pragma mark - UIViewControllerPreviewingDelegate

-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
    NSIndexPath *indexPath=[self.tableView indexPathForRowAtPoint:location];
    
    if(indexPath)
    {
        
        DFBaseLineCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        if (cell && [cell isKindOfClass:[DFTextImageLineCell class]]) {
            DFTextImageLineCell *imageCell = (DFTextImageLineCell *)cell;
            //            NSInteger index = [imageCell getIndexFromPoint:location];
            
            DFBaseLineItem *item = [_items objectAtIndex:indexPath.row];
            if (item && [item isKindOfClass:[DFTextImageLineItem class]]) {
                DFTextImageLineItem *textItem = (DFTextImageLineItem *) item;
                if (index == -1) {
                    return nil;
                }
                NSString *url  = [textItem.srcImages objectAtIndex:index];
                DFImagePreviewViewController *previewController=[[DFImagePreviewViewController alloc] initWithImageUrl:url itemId:item.content_id];
                previewController.delegate = self;
                previewController.preferredContentSize=CGSizeMake(300, 300);
                return previewController;
            }
        }
    }
    return nil;
}
-(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
{
    [self showViewController:viewControllerToCommit sender:self];
}

@end
